package com.springboot.frame.comm.render;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * Freemarker模板渲染
 *
 * @author madman
 */
@Slf4j
@Data
@AllArgsConstructor
public class FreemarkerRender implements Render {

  /**
   * freemarker引擎
   */
  private static final Configuration ENGINE = new Configuration(Configuration.getVersion());

  static {
    ENGINE.setClassForTemplateLoading(FreemarkerRender.class, "/");
    ENGINE.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
  }

  /**
   * 模板路径
   */
  private String templatePath;

  @Override
  public void process(Map<String, Object> renderData, Writer writer) throws IOException {
    try {
      ENGINE.getTemplate(templatePath).process(renderData, writer);
    } catch (TemplateException e) {
      log.error("获取模板失败，模板路径为{}", templatePath);
    }
  }

}
